package com.itheima.controller.backend.security.admin;


import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.Result;
import com.itheima.common.pojo.Setmeal;
import com.itheima.common.pojo.dto.SetmealPageQueryDTO;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private AliOssUtil ossClient;

    /**
     * 添加套餐
     * @param setmeal
     * @return
     */
    @PostMapping("/add")
    public Result save(@RequestBody Setmeal setmeal, @RequestParam String checkgroupIds){
        log.info("添加套餐，套餐信息：{}，检查组ids：{}", setmeal, checkgroupIds);
        
        try {
            // 1. 检查图片URL是否为空
            if (setmeal.getImg() == null || setmeal.getImg().trim().isEmpty()) {
                return new Result(false, "请先上传图片");
            }
            
            // 2. 验证图片URL是否是有效的阿里云地址
            if (!setmeal.getImg().startsWith("https://") || !setmeal.getImg().contains("aliyuncs.com")) {
                return new Result(false, "图片地址无效");
            }
            
            // 3. 验证图片是否真实存在于OSS中（需要注入AliOssUtil）
            String objectName = extractObjectNameFromUrl(setmeal.getImg());
            if (!ossClient.doesObjectExist(objectName)) {
                return new Result(false, "图片不存在，请重新上传");
            }
            
            // 4. 保存套餐信息
            setmealService.save(setmeal, checkgroupIds);
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            log.error(MessageConstant.ADD_SETMEAL_FAIL, e);
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL + e.getMessage());
        }
    }

    private String extractObjectNameFromUrl(String imageUrl) {
        // 从URL中提取对象名称
        String urlWithoutProtocol = imageUrl.substring(imageUrl.indexOf("//") + 2);
        return urlWithoutProtocol.substring(urlWithoutProtocol.indexOf("/") + 1);
    }

    /**
     * 删除套餐
     * @param ids 要删除的套餐id，多个id用逗号分隔
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable String ids){
        log.info("删除套餐，ids：{}", ids);
        try {
            if (ids == null || ids.trim().isEmpty()) {
                return new Result(false, "请选择要删除的套餐");
            }
            
            List<Integer> idList = Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
                    
            if (idList.isEmpty()) {
                return new Result(false, "请选择要删除的套餐");
            }
            
            setmealService.deleteBatch(idList);
            return new Result(true, MessageConstant.DELETE_SETMEAL_SUCCESS);
        } catch (NumberFormatException e) {
            log.error("删除套餐失败，参数格式错误：{}", e.getMessage());
            return new Result(false, MessageConstant.SETMEAL_ID_ERROR);
        } catch (Exception e) {
            log.error("删除套餐失败：{}", e.getMessage());
            return new Result(false, MessageConstant.DELETE_SETMEAL_FAIL + e.getMessage());
        }
    }

    /**
     * 修改套餐
     * @param setmeal
     * @param checkGroupIds
     * @return
     */
    @PostMapping("/edit")
    public Result update(@RequestBody Setmeal setmeal, @RequestParam String checkGroupIds) {
        try {
            setmealService.update(setmeal, checkGroupIds);
            return new Result(true, MessageConstant.EDIT_SETMEAL_SUCCESS);
        } catch (Exception e) {
            log.error("更新套餐失败", e);
            return new Result(false, MessageConstant.EDIT_SETMEAL_FAIL + ": " + e.getMessage());
        }
    }

    /**
     * 分页查询套餐
     * @param setmealDTO
     * @return
     */
    @PostMapping("/findPage")
    public PageResult page(@RequestBody SetmealPageQueryDTO setmealDTO){
        log.info("分页查询套餐");
        PageResult pageResult = setmealService.pageQuery(setmealDTO);
        return pageResult;
    }

    /**
     * 根据套餐id查询套餐关联的检查组
     * @param setmealId
     * @return
     */
    @GetMapping("/findCheckGroupListBySetmealId/{setmealId}")
    public Result findCheckGroupListBySetmealId(Integer setmealId){
        log.info("根据套餐id查询套餐关联的检查组");
        List<Integer> checkGroupIds = setmealService.findCheckGroupIdsBySetmealId(setmealId);
        return new Result(true,MessageConstant.GET_GROUP_LIST_SUCCESS,checkGroupIds);
    }

    /**
     * 根据套餐id查询套餐
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Result findById(@RequestParam Integer id){
        log.info("根据套餐id查询套餐");
        Setmeal setmeal = setmealService.findById(id);
        return new Result(true,MessageConstant.GET_SETMEAL_LIST_SUCCESS,setmeal);
    }

}

